package com.zhl.common.service;

import com.zhl.common.anno.IoAnno;
import com.zhl.common.domain.AbstractUpFileRQ;
import com.zhl.common.domain.AlibabaUpFileRQ;
import com.zhl.common.enums.IoEnum;
import com.zhl.common.exception.BusinessException;
import com.zhl.common.utils.OSSUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @description 阿里云oss文件处理实现
 * @Author: z156940l@outlook.com
 * @className AlibabaFileService
 * @Date: 2024/7/21 14:06
 */
@IoAnno(type = IoEnum.ALIBABA_CLOUD)
public class AlibabaFileService extends AbstractFileService {

    private final OSSUtils ossUtils;

   public AlibabaFileService(OSSUtils ossUtils){
       this.ossUtils = ossUtils;
   }

    @Override
    public String upFile(AbstractUpFileRQ abstractUpFileRQ) {
        AlibabaUpFileRQ rq = (AlibabaUpFileRQ) abstractUpFileRQ;
        String url = null;
        try {
            String bas64 = rq.getBas64();
            bas64 = bas64.replaceAll("[\\s*\t\n\r]", "");
            // 解码Base64字符串为字节数组
            byte[] decodedBytes = Base64.getDecoder().decode(bas64);
            // 将字节数组包装成InputStream对象
            InputStream inputStream = new ByteArrayInputStream(decodedBytes);
            url = ossUtils.uploadInputStream(inputStream, rq.getName(), rq.getSize());
            inputStream.close();
        } catch (IOException e) {
            throw new BusinessException("请求三方服务文件异常!");
        }
        return url;
    }

    @Override
    public String showUrl(String key) {
        return ossUtils.queryImgUrl(key);
    }
}
